package com.mj.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.UnsupportedEncodingException;

/**
 * Created by SXY on 2016/1/8.
 */
public class StringEncodeUtil {

    private static final Log logger = LogFactory.getLog(StringEncodeUtil.class);

    public static String getCharEncode(String str){

        String charEncode = "UTF-8";
        try {
            if(str.equals(new String(str.getBytes(),charEncode))){

                return charEncode;
            }
        } catch (UnsupportedEncodingException e) {

        }
        charEncode = "GB2312";
        try {
            if(str.equals(new String(str.getBytes(),charEncode))){

                return charEncode;
            }
        } catch (UnsupportedEncodingException e) {

        }


        charEncode = "GBK";
        try {
            if(str.equals(new String(str.getBytes(),charEncode))){

                return charEncode;
            }
        } catch (UnsupportedEncodingException e) {

        }

        charEncode = "ISO-8859-1";
        try {
            if(str.equals(new String(str.getBytes(),charEncode))){

                return charEncode;
            }
        } catch (UnsupportedEncodingException e) {

        }


        return "";

    }

    /**
    * 转成GBK编码
    * @param str
    * @return
     */
    public static String transcodeToGBK(String str){
        return transcode(str,"GBK");
    }

    /**
     * 转成UTF-8编码
     * @param str
     * @return
     */
    public static String transcodeToUTF_8(String str){
        return transcode(str,"UTF-8");
    }

    /**
     * 自动转码
     * @param str
     * @param charEncode 默认UTF-8
     * @return
     */
    public static String transcode(String str,String charEncode){

        if(null==charEncode||"".equals(charEncode)){
            charEncode = "UTF-8";
        }

        String temp = "";
        try {
            String code = getCharEncode(str);
            logger.info("编码："+code);
            temp = new String(str.getBytes(code),charEncode);
        } catch (UnsupportedEncodingException e) {
            logger.info("转码异常："+e.getMessage());
        }
        return temp;
    }
}
